import schedule
import time
import sys
import os
import configparser
import logging
from libs.task import Task


class Main:

    config = None
    ssl_dir = None

    def init(self):
        self.config = self.checkConfig()
        if (self.config == False):
            sys.exit()

        # 运行一次后再加入到定时任务中
        self.job()

        # 设置定时任务并运行，可自行决定任务的运行时间
        # schedule.every(1000).seconds.do(job)
        taskTime = self.config['main']['taskTime']
        if taskTime is None or taskTime == "":
            taskTime = "03:01"

        schedule.every().day.at(taskTime).do(self.job)
        while True:
            schedule.run_pending()
            time.sleep(1)

    def checkConfig(self):

        self.ssl_dir = os.path.join(os.path.dirname(
            os.path.realpath(__file__)), f"ssls")
        logs_dir = os.path.join(os.path.dirname(
            os.path.realpath(__file__)), f"logs")
        ini_dir = os.path.join(os.path.dirname(
            os.path.realpath(__file__)), f"conf.ini")

        os.makedirs(f"{self.ssl_dir}", exist_ok=True)
        os.makedirs(f"{logs_dir}", exist_ok=True)

        # 日志配置
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s[%(levelname)s]: %(message)s',
                            filename=f'{logs_dir}/app.log',
                            filemode='w')

        logging.info('应用启动...')

        if os.path.exists(ini_dir) == False:
            print('初始化 Ini 文件。')
            self.initConfig(ini_dir)
            task = Task()
            task.initSite()
            sys.exit()

        # 配置文件检查
        config = configparser.ConfigParser()
        config.read(ini_dir)

        # 检查节点
        section = ['main', 'aliyun', 'tencent', 'email']
        iniSection = []
        for conf in config.sections():
            iniSection.append(conf)

        set1 = set(section)
        set2 = set(iniSection)

        if set1 == set2:
            print('配置检查完成...')
            return config
        else:
            print('ini节点不符...')
            return False

    def initConfig(self, ini_dir):
        # 创建一个新的ConfigParser对象
        config = configparser.ConfigParser()

        # 添加更多的sections和options
        config['main'] = {}
        config['main']['appName'] = '任务执行01'
        config['main']['sendMail'] = 'ON'
        config['main']['taskTime'] = '03:00'

        config['aliyun'] = {}
        config['aliyun']['AccessKeyId'] = ''
        config['aliyun']['AccessKeySecret'] = ''

        config['tencent'] = {}
        config['tencent']['SecretId'] = ''
        config['tencent']['SecretKey'] = ''

        config['email'] = {}
        config['email']['MAIL_RECEIVER'] = ''
        config['email']['MAIL_RECEIVER_LEVEL'] = ''
        config['email']['MAIL_HOST'] = ''
        config['email']['MAIL_PORT'] = ''
        config['email']['MAIL_USER'] = ''
        config['email']['MAIL_PASS'] = ''
        config['email']['MAIL_SENDER'] = ''

        # 保存修改后的配置到INI文件
        with open(ini_dir, 'w') as file:
            config.write(file)
        print(f'初始化完成，需要配置相关项目。请正确填写conf.ini与sites.json')

    def job(self):
        print("working...")
        task = Task()
        task.job(self.config, self.ssl_dir)


if __name__ == "__main__":
    main = Main()
    main.init()
